/**
 * 集群模块控制器
 * 
 * @author zhongfuhua
 */

var jobDetailApp = angular.module("jobDetailApp", ["publicServiceApp","jobDetailServiceApp", "jobDetailParamServiceApp", "jobServiceApp", 
								"jobDetailTrackServiceApp", "jobDetailDeathServiceApp", "ngJsTree", "ngSelect2"]);

jobDetailApp.controller("jobDetailCtrl", [
		"$scope",
		"commonService",
		"publicService",
		"jobDetailService",
		"jobDetailParamService",
		"jobService",
		"jobDetailTrackService",
		"$timeout",
		"$log",
		function($scope, commonService, publicService, jobDetailService, jobDetailParamService, jobService, jobDetailTrackService, $timeout, $log) {
			
			
			// 表格
			$scope.$jobDetailTable = $('#jobDetailTable');
			
			// 按钮
			$scope.$jobDetailAddButton = $('#jobDetailAddButton');
			$scope.$jobDetailRemoveButton = $('#jobDetailRemoveButton');
			$scope.$jobDetailStopButton = $('#jobDetailStopButton');
			$scope.$jobDetailResumeButton = $('#jobDetailResumeButton');
			
			
			// 模态框
			$scope.$jobDetailModal = $('#jobDetailModal');
			$scope.$jobDetailConfigModal = $('#jobDetailConfigModal');
			$scope.$jobDetailParamModal = $('#jobDetailParamModal');
			
			// 表格选中实例对象
			$scope.selectionIds = new Array();
			$scope.selections = new Array();
			
			
			// 监视isSucce的状态
			$scope.action = null;
			$scope.isSuccess = true;
			$scope.error = null;
			
			// vo
			$scope.userName = null;
			$scope.publicVO = {};
			$scope.jobDetailParamVO = {};
			
			$scope.jobDetailVO = {
				params : [{mkey : "", mvalue : ""}],
				jobDetailAddType : "alone",
				modelBeginValue : 0,
				batchBeginValue : 0,
				running : 1,
				batchNum : 10,
				modelNum : 10,
				name : null
			};
			
			$scope.jobDetailParamTableCurrent = null;
			
			$scope.jobSelectConfig = {
					minimumResultsForSearch : 1, // 是否打开搜索
					data : [],			 
					placeholder : '如无选项请新增任务'			 // 占位符
			};
			
			$scope.runStatusSelectConfig = {
					minimumResultsForSearch : 1, // 是否打开搜索
					data : [{text:"已接收",id:"RECIVE"},
                            {text:"离线",id:"OFFLINE"},
                            {text:"离线超时",id:"OFFLINE_TIMEOUT"},
                            {text:"超时",id:"TIMEOUT"}
                           ],			 
					placeholder : '请选择'			 // 占位符
			};
			
			
			$scope.buildTypeSelectConfig = {
					minimumResultsForSearch : 1, // 是否打开搜索
					data : [{text:"单独添加",id:"alone"},
                            {text:"批量添加",id:"batch"},
                            {text:"批量分片键添加",id:"sliceBatch"}],			 
					placeholder : '请选择'			 // 占位符
			};
			
			ffc.util.watchResult($scope, $timeout);
			
			
			/**
			 * 
			 * 功能说明:查询子任务
			 * 
			 */
			$scope.queryJobDetail = function(){
				$scope.$jobDetailTable.bootstrapTable("selectPage", 1);  
			}
			
			/**
			 * 
			 * 功能说明:查询参数
			 * 
			 */
			$scope.queryJobDetailParam = function(){
				if($scope.jobDetailParamTableCurrent != null &&  $scope.jobDetailParamTableCurrent != undefined){
					$scope.jobDetailParamTableCurrent.bootstrapTable("selectPage", 1);  
				}
			}
			
			
			
			/**
			 * 
			 * 功能说明:新增子任务
			 * 
			 */
			$scope.addJobDetail = function(){
				if($scope.jobDetailForm.$invalid){
					new MessageDialog().error("配置填写不规范，请重新填写！！！")
					return;
				}
				var oparam = new Array();
				$.each($scope.jobDetailVO.params, function(index,value){
					if(!ffc.util.isEmpty(value.mkey) && !ffc.util.isEmpty(value.mkey)){
						var param = {
							mkey : value.mkey,
							mvalue : value.mvalue,
							clusterName : $scope.jobDetailVO.job.clusterName
						}
						oparam.push(param);
					}
				});
				$scope.jobDetailVO.params = oparam;
				$scope.jobDetailVO.clusterName = $scope.jobDetailVO.job.clusterName;	
				jobDetailService.add($scope.jobDetailVO, function(result){
					if(!result.result){
						$scope.error = result.msgTitle;
						$scope.isSuccess = false;
						return false;
					}
					new MessageDialog().success("添加成功!!");
					$scope.$jobDetailModal.modal("hide");
					$scope.queryJobDetail();
				},function(error){
					$scope.error = error;
					$scope.isSuccess = false;
				});
			}
			
			
			/**
			 * 
			 * 功能说明:删除子任务
			 * 
			 */
			$scope.deleteJobDetail = function(){
				new MessageDialog().confirm("确定删除？", function() {
					var deleteObjs = new Array();
					angular.forEach($scope.selections, function(data, index, array){
						deleteObjs.push({
							id : data.id, 
							clusterName : data.clusterName,
							jobName : data.jobName,
							name : data.name
						});
					});
					
					jobDetailService.removeList($scope.selections, function(result){
						if(!result.result){
							$scope.error = result.msgTitle;
							$scope.isSuccess = false;
							return false;
						}
						new MessageDialog().alert("删除成功");
						$scope.queryJobDetail();
					},function(error){
						$scope.error = error;
						$scope.isSuccess = false;
					});
			   });
			}
			
			
			/**
			 * 
			 * 功能说明:添加参数输入文本框
			 * 
			 */
			$scope.addParamInput = function(){
				$scope.jobDetailVO.params.push({mkey : "", mvalue : ""});
			}
			
			
			/**
			 * 
			 * 功能说明:删除指定参数输入文本框
			 * 
			 */
			$scope.removeParamInput = function(param){
				angular.forEach($scope.jobDetailVO.params, function(data, index, array){
					if(param == data){
						array.splice(index, 1);
					}
				});
			}

			
			/**
			 * 
			 * 功能说明:查询任务组下拉框数据
			 * 
			 */
			$scope.queryJobSelect = function(){
				jobService.query({}, function(result){
					if(!result.result){
						$scope.error = result.msgTitle;
						$scope.isSuccess = false;
						return false;
					}
					$scope.jobSelectConfig.data  = new Array();
					angular.forEach(result.dataList, function(data, index, array){
						var option = {
							id : data.id,
							text : data.name,
							clusterName : data.clusterName
						}
						$scope.jobSelectConfig.data.push(option);
					});
					ffc.util.angularApply($scope, $timeout);
				},function(error){
					$scope.error = error;
					$scope.isSuccess = false;
				});
			}
			
			
			/**
			 * 
			 * 功能说明:查询任务组下拉框数据
			 * 
			 */
			$scope.queryJobDetailThreadInfo = function(){
				jobDetailService.queryThreadInfo($scope.jobDetailRunningVO, function(result){
					if(!result.result){
						$scope.error = result.msgTitle;
						$scope.isSuccess = false;
						return false;
					}
					$scope.jobDetailThreadInfoVO.jobProcessThread = result.object.jobProcessThread;
					$scope.jobDetailThreadInfoVO.jobProcessBusinessThread = result.object.jobProcessBusinessThread;
					ffc.util.angularApply($scope, $timeout);
				},function(error){
					$scope.error = error;
					$scope.isSuccess = false;
				});
			}
			
			
			/**
			 * 
			 * 功能说明:暂停子任务
			 * 
			 */
			$scope.pauseJobDetail = function(){
				new MessageDialog().confirm("确定暂停子任务？", function() {
					jobDetailService.pauseList($scope.selections, function(result){
						if(!result.result){
							$scope.error = result.msgTitle;
							$scope.isSuccess = false;
							return false;
						}
						new MessageDialog().alert("暂停成功!!");
						$scope.queryJobDetail();
					},function(error){
						$scope.error = error;
						$scope.isSuccess = false;
					});
			   });
			}
			
			
			/**
			 * 
			 * 功能说明:唤醒子任务
			 * 
			 */
			$scope.resumeJobDetail = function(){
				new MessageDialog().confirm("确定唤醒子任务？", function() {
					jobDetailService.resumeList($scope.selections, function(result){
						if(!result.result){
							$scope.error = result.msgTitle;
							$scope.isSuccess = false;
							return false;
						}
						new MessageDialog().alert("唤醒成功!!");
						$scope.queryJobDetail();
					},function(error){
						$scope.error = error;
						$scope.isSuccess = false;
					});
			   });
			}
			
			
			$scope.deleteJobDetailParam = function(){
				new MessageDialog().confirm("确定删除参数？", function() {
					jobDetailParamService.remove($scope.jobDetailParamVO, function(result){
						if(!result.result){
							$scope.error = result.msgTitle;
							$scope.isSuccess = false;
							return false;
						}
						new MessageDialog().alert("删除成功!!");
						$scope.queryJobDetailParam();
					},function(error){
						$scope.error = error;
						$scope.isSuccess = false;
					});
			   });
			}
			
			
			$scope.saveJobDetailParam = function(){
				if($scope.actionJobDetailParam=="MOD"){
					jobDetailParamService.update($scope.jobDetailParamVO, function(result){
						if(!result.result){
							$scope.error = result.msgTitle;
							$scope.isSuccess = false;
							return false;
						}
						new MessageDialog().alert("修改成功!!");
						$scope.$jobDetailParamModal.modal("hide");
						$scope.queryJobDetailParam();
					},function(error){
						$scope.error = error;
						$scope.isSuccess = false;
					});
				}else{
					jobDetailParamService.add($scope.jobDetailParamVO, function(result){
						if(!result.result){
							$scope.error = result.msgTitle;
							$scope.isSuccess = false;
							return false;
						}
						new MessageDialog().alert("添加成功!!");
						$scope.$jobDetailParamModal.modal("hide");
						$scope.queryJobDetailParam();
					},function(error){
						$scope.error = error;
						$scope.isSuccess = false;
					});
				}
				
			}
			
			
			/**
			 * 
			 * 功能说明:查询所有菜单，父子结构展示
			 * 
			 * @author ZHONGFUHUA
			 * 
			 * @Date 2016年10月20日
			 * 
			 */
			$scope.queryCurrentUser = function(){
				publicService.queryCurrentUser({}, function(data) {
					$scope.userName = data.userName;
				}, function(error) {
					$scope.error = error;
					$scope.isSuccess = false;
				});
			}
			
			$(function() {
				
				$scope.queryJobSelect();
				$scope.queryCurrentUser();
				
				/**
				 * 
				 * 功能说明:初始化数据源表格
				 * 
				 */
				$scope.$jobDetailTable.bootstrapTable({
					queryParams : function(params) {
						var selfParams = {
							name : $scope.jobDetailVO.queryName,
							jobId : $scope.jobDetailVO.queryJobId
						}
						return $.extend({}, params, selfParams);
					},
					ajax : function(render) {
						jobDetailService.queryPage(render.data, function(result) {
							if(!result.result){
								$scope.error = result.msgTitle;
								$scope.isSuccess = false;
								return false;
							}
							ffc.util.loadTableData(render, result);  
						},function(error){
							$scope.error = error;
							$scope.isSuccess = false;
						});
						$scope.$jobDetailRemoveButton.prop('disabled', true);
						$scope.$jobDetailStopButton.prop('disabled', true);
						$scope.$jobDetailResumeButton.prop('disabled', true);
					},
					onExpandRow : function(index, row, $detail){
						var jobDetailParamTable = $detail.html(
								"<div class=\"table-responsive\">" +
									"<table name='jobDetailParamTable'></table>" +
								"</div>"
								).find("table");
						
						var columns = [];
						
						columns.push({
							field : "mkey",
							title : "参数名",
							width : "30%",
							align : "center",
							classes : "table-column",
							valign : "middle"
						});
						
						columns.push({
							field : "mvalue",
							title : "参数值",
							width : "30%",
							align : "center",
							classes : "table-column",
							valign : "middle"
						});
						
						columns.push({
							title : "操作",
							width : "40%",
							align : "center",
							classes : "table-column operation",
							valign : "middle",
							formatter : jobDetailParamFormatter,
							events : jobDetailParamEvents
						});
						
						$scope.jobDetailParamTableCurrent = jobDetailParamTable;
						
						jobDetailParamTable.bootstrapTable({
							idField : "id",
							sidePagination: "server",
							columns : columns,
							pagination : true,
							pageList : [5, 10, 20],
							detailView : false,
							queryParamsType : "",
							queryParams : function(params) {
								var selfParams = {
									jobDetailId : row.id,
									clusterName : row.clusterName
								};
								return $.extend({}, params, selfParams);
							},
							ajax : function(render) {
								jobDetailParamService.queryPage(render.data, function(result) {
									if(!result.result){
										$scope.error = result.msgTitle;
										$scope.isSuccess = false;
										return false;
									}
									ffc.util.loadTableData(render, result);  
								},function(error){
									$scope.error = error;
									$scope.isSuccess = false;
								});
							}
						});
					}
				});
				
				
				
				/**
				 * 
				 * 功能说明:每次选择时重新获取表格中被选中对象
				 * 
				 */
				$scope.$jobDetailTable.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table',function () {
					$scope.$jobDetailRemoveButton.prop('disabled', !$scope.$jobDetailTable.bootstrapTable('getSelections').length);
					$scope.$jobDetailStopButton.prop('disabled', !$scope.$jobDetailTable.bootstrapTable('getSelections').length);
					$scope.$jobDetailResumeButton.prop('disabled', !$scope.$jobDetailTable.bootstrapTable('getSelections').length);
					$scope.selectionIds = new Array();
					$scope.selections = new Array();
					angular.forEach($scope.$jobDetailTable.bootstrapTable('getSelections'), function(data, index, array) {
						$scope.selectionIds.push(data.id);
						$scope.selections.push(data);
					});
				})
								
				
				/**
				 * 
				 * 功能说明:弹出框打开事件
				 * 
				 */
				$scope.$jobDetailModal.on('shown.bs.modal',function(){
					$scope.jobDetailVO = {
						params : [{mkey : "", mvalue : ""}],
						jobDetailAddType : "alone",
						modelBeginValue : 0,
						batchBeginValue : 0,
						running : 1,
						batchNum : 10,
						modelNum : 10,
						name : null
					};
					$scope.jobDetailForm.$setPristine();
				});
				
				
				/**
				 * 
				 * 功能说明:弹出框关闭事件
				 * 
				 */
				$scope.$jobDetailModal.on("hidden.bs.modal",function(){
					$scope.action = null;
					var queryName = $scope.jobDetailVO.queryName;
					var queryJobId = $scope.jobDetailVO.queryJobId;
					
					$scope.jobDetailVO = {
						queryName : queryName,
						queryJobId : queryJobId,
						params : [{mkey : "", mvalue : ""}],
						jobDetailAddType : "alone",
						modelBeginValue : 0,
						batchBeginValue : 0,
						running : 1,
						batchNum : 10,
						modelNum : 10
					};
					$scope.jobDetailForm.$setPristine();
				});
				
				/**
				 * 
				 * 功能说明:弹出框关闭事件
				 * 
				 */
				$scope.$jobDetailParamModal.on("hidden.bs.modal",function(){
					$scope.actionJobDetailParam == null;
					$scope.jobDetailParamVO = {};
					$scope.jobDetailParamForm.$setPristine();
				});

				
				
				/**
				 * 
				 * 功能说明:弹出框打开事件
				 * 
				 */
				$scope.$jobDetailParamModal.on('shown.bs.modal',function(){
					if($scope.actionJobDetailParam == "MOD"){
						$("#jobDetailParamModal [name='mkey']").attr("readonly", "readonly");
					}else{
						$("#jobDetailParamModal [name='mkey']").removeAttr("readonly");
					}
				});
				
				
				
				
				
				/**
				 * 
				 * 功能说明:格式化表格输出
				 * 
				 */
				jobDetailOperFormatter = function(value, row, index) {
					 var button = "<button type=\"button\" class=\"btn btn-xs btn-info\" style=\"margin-right: 3px;\" title=\"运行中的子任务\"><i class=\"glyphicon glyphicon-cog\"></i> 配置</button>"+
					 			 "<button type=\"button\" class=\"btn btn-xs btn-blue\" style=\"margin-right: 3px;\" title=\"添加参数\"><i class=\"glyphicon glyphicon-plus-sign\"></i> 参数</button>"+
						 		 "<button type=\"button\" class=\"btn btn-xs btn-success\" style=\"margin-right: 3px;\"  title=\"运行中的子任务\">运行中</button>"+
						         "<button type=\"button\" class=\"btn btn-xs btn-warning\" style=\"margin-right: 3px;\"  title=\"待重试的子任务\">待执行</button>"+
						         "<button type=\"button\" class=\"btn btn-xs btn-danger\" style=\"margin-right: 3px;\"  title=\"已卡死的子任务\">死任务</button>";
					return button;
				}
				
				/**
				 * 
				 * 功能说明:格式化表格输出
				 * 
				 */
				filedRunningFormatter = function(value, row, index) {
					if(value == 'NONE'){
						return "无";
					}else if(value == 'PAUSED'){
						return "暂停"
					}else if(value == 'NORMAL'){
						return "正常"
					}else if(value == 'COMPLETE'){
						return "完成"
					}else if(value == 'ERROR'){
						return "错误"
					}else if(value == 'BLOCKED'){
						return "执行中"
					}
					return value;
				}
				
				/**
				 * 
				 * 功能说明:格式化表格输出
				 * 
				 */
				statusFormatter = function(value, row, index) {
					if(value == 'FIRE'){
						return "已触发";
					}else if(value == 'SEND'){
						return "已发送"
					}else if(value == 'RECIVE'){
						return "送达"
					}else if(value == 'COMPLETE'){
						return "完成"
					}else if(value == 'OFFLINE'){
						return "离线"
					}else if(value == 'TIMEOUT'){
						return "超时"
					}else if(value == 'OFFLINE_TIMEOUT'){
						return "离线超时"
					}
					return value;
				}
				
				
				/**
				 * 
				 * 功能说明:格式化表格输出
				 * 
				 */
				jobDetailParamFormatter = function(value, row, index) {
					return "<a class=\"operation-update\"><i class=\"glyphicon glyphicon-pencil\"></i>修改</a>"+
					   "<a class=\"line\">|</a>" +
					   "<a class=\"operation-del\"><i class=\"glyphicon glyphicon-trash\"></i>删除</a>";
				}
				
				
				/**
				 * 
				 * 功能说明:格式化事件
				 * 
				 */
				jobDetailParamEvents = {
					'click .operation-update' : function(e, value, row, index) {
						$scope.jobDetailParamVO = {};
						angular.copy(row, $scope.jobDetailParamVO);
						$scope.actionJobDetailParam = "MOD";
						ffc.util.angularApply($scope, $timeout);
						$scope.$jobDetailParamModal.modal("show");
					},
					'click .operation-del' : function(e, value, row, index) {
						$scope.jobDetailParamVO = {};
						angular.copy(row, $scope.jobDetailParamVO);
						$scope.deleteJobDetailParam();
					}
				};
				
				
				/**
				 * 
				 * 功能说明:格式化事件
				 * 
				 */
				jobDetailOperEvents = {
					'click .btn-info' : function(e, value, row, index) {
						$scope.jobDetailVO = {};
						angular.copy(row, $scope.jobDetailVO);
						ffc.util.angularApply($scope, $timeout);
						$scope.$jobDetailConfigModal.modal("show");
					},
					'click .btn-blue' : function(e, value, row, index) {
						$scope.jobDetailParamVO = {};
						$scope.jobDetailParamVO.jobDetailId = row.id;
						$scope.jobDetailParamVO.clusterName = row.clusterName;
						$scope.actionJobDetailParam = 'ADD';
						ffc.util.angularApply($scope, $timeout);
						$scope.$jobDetailParamModal.modal("show");
					},
					'click .btn-success' : function(e, value, row, index) {
						$scope.publicVO.jobDetailRunningInit(row);
					},
					'click .btn-warning' : function(e, value, row, index) {
						$scope.publicVO.jobDetailRetryInit(row);
					},
					'click .btn-danger' : function(e, value, row, index) {
						$scope.publicVO.jobDetailDeathInit(row);
					}
				};
				
				
				
				/**
				 * 
				 * 功能说明:日期格式化
				 * 
				 */
				$('.date').datetimepicker({
		            format: 'yyyy-MM-dd hh:mm:ss',
		            dateIcon: 'glyphicon glyphicon-calendar'
		        });
				
			});
}]);
